package com.qiantu.phone.ui.activity;

import static com.qiantu.phone.BuildConfig.OBS_BASE;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.manager.OBSManager;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.lxj.xpopup.XPopup;
import com.qiantu.phone.utils.GetJsonDataUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class RoomSettingActivity extends AppActivity {

    private static final int EDIT_ROOM_CODE = 666;
    private String floorName;
    private String roomName;
    private String roomSerialNo;
    private String floorSerialNo;
    private String roomType;
    private int floorType;
    private int shareCount;
    private BottomEditDialog mBottomEditDialog;
    private TextView tvRoomName;
    private TextView tvRoomType;
    private TextView tvFloorName;
    private TextView tvSceneNum;
    private TextView tvDeviceNum;
    private TextView tvShareCount;
    private View btnFloor;
    private Map roomIconType;
    private BottomListDialog mBottomListDialog;
    private String currentAction;

    @Override
    protected int getLayoutId() {
        return R.layout.room_setting_activity;
    }

    @Override
    protected void initView() {
        roomSerialNo = getIntent().getStringExtra("roomSerialNo");
        floorSerialNo = getIntent().getStringExtra("floorSerialNo");
        floorType = getIntent().getIntExtra("floorType", 0);
        roomName = getIntent().getStringExtra("roomName");
        floorName = getIntent().getStringExtra("floorName");
        roomType = getIntent().getStringExtra("roomType");
        tvRoomName = findViewById(R.id.tv_room_name);
        tvRoomType = findViewById(R.id.tv_room_type);
        tvFloorName = findViewById(R.id.tv_floor_name);
        btnFloor = findViewById(R.id.btn_floor);
        tvSceneNum = findViewById(R.id.tv_scene_num);
        tvDeviceNum = findViewById(R.id.tv_device_num);
        tvShareCount = findViewById(R.id.tv_share_count);
//        initViewPager();
        setOnClickListener(R.id.btn_room, R.id.btn_floor, R.id.btn_delete, R.id.btn_enviroment, R.id.btn_type,R.id.btn_picture,R.id.btn_share);
        List<SceneBean> scenes = LLSceneDBManager.getInstance(getContext()).getSceneByRoom(roomSerialNo);
        List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getDeviceByRoom(roomSerialNo);
        //默认楼层不显示
        if(floorType == 1){
            btnFloor.setVisibility(View.GONE);
        }else{
            btnFloor.setVisibility(View.VISIBLE);
        }
        tvSceneNum.setText(scenes.size() + "");
        tvDeviceNum.setText(devices.size() + "");
        tvShareCount.setText(shareCount + "");
    }

    private void updateRoomName(){
        tvFloorName.setText(floorName);
        tvRoomName.setText(roomName);
        tvShareCount.setText(shareCount+"");
        Map iconInfo = (Map) roomIconType.get(roomType);
        tvRoomType.setText(iconInfo.get("name").toString());
    }

    @Override
    protected void initData() {
        LLHttpManager.getRoomInfo((LifecycleOwner) getContext(), roomSerialNo, new HttpCallback<HttpData<RoomBean>>(null){
            @Override
            public void onSucceed(HttpData<RoomBean> result) {
                shareCount = result.getData().getShareCount();
                String jsonDataStr = new GetJsonDataUtil().getJson(getContext(), "RoomType.json");//获取assets目录下的json文件数据
                roomIconType = new Gson().fromJson(jsonDataStr, new TypeToken<Map>() {}.getType());
                updateRoomName();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                toast("修改失败");
            }
        });

    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showDeleteHintDialog() {
        if (mConfirmCancelHintDialog ==  null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                Map data = new HashMap<>();
                //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
                data.put("roomSerialNo", roomSerialNo);
                LLHttpManager.deleteRoom(RoomSettingActivity.this, data,
                        new HttpCallback<HttpData<Void>>(RoomSettingActivity.this) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(null);
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                if (result.isRequestSucceed()) {
                                    LLRoomDBManager.getInstance(getContext()).remove(roomSerialNo);
                                    LLDeviceDBManager.getInstance(getContext()).updateCommonDeviceByDeleteRoomSerialNo(roomSerialNo);
                                    EventBus.getDefault().post(new RefreshDeviceListEvent());
                                    EventBus.getDefault().post(new RefreshFloorRoomEvent());
                                    toast(R.string.delete_success);
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }
                        });
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.delete_room_hint));
        mConfirmCancelHintDialog.show();
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String text = mBottomEditDialog.getText();
                    if(TextUtils.isEmpty(text)){
                        toast("请输入房间名称");
                        return;
                    }
                    LLHttpManager.editRoom((LifecycleOwner) getContext(), roomSerialNo, floorSerialNo, text, roomType, new HttpCallback<HttpData<Void>>(null){
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            roomName = mBottomEditDialog.getText();
                            tvRoomName.setText(roomName);
                            LLRoomDBManager.getInstance(getContext()).editRoomInfo(roomSerialNo, text, floorSerialNo, roomType);
                            EventBus.getDefault().post(new RefreshFloorRoomEvent());
                            setResult(RESULT_OK);
                            toast(R.string.reset_success);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            toast("修改失败");
                        }
                    });
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.room_name));
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.ROOM_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    @Override
    public void onResume(){
        super.onResume();
        initData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_room:
                showBottomEditDialog(tvRoomName.getText().toString());
                break;
            case R.id.btn_floor:
                Intent intent = new Intent(this, SelectFloorActivity.class);
                intent.putExtra("roomName", roomName);
                intent.putExtra("roomSerialNo", roomSerialNo);
                intent.putExtra("floorSerialNo", floorSerialNo);
                intent.putExtra("roomType", roomType);
                startActivityForResult(intent, EDIT_ROOM_CODE);
                break;
            case R.id.btn_delete:
                showDeleteHintDialog();
                break;
            case R.id.btn_enviroment:
                Intent intent1 = new Intent(this, RoomEnviromentActivity.class);
                intent1.putExtra("roomSerialNo", roomSerialNo);
                startActivity(intent1);
                break;
            case R.id.btn_type:
                Intent roomIntent = new Intent(this, RoomTypeActivity.class);
                roomIntent.putExtra("roomSerialNo", roomSerialNo);
                roomIntent.putExtra("roomType", roomType);
                roomIntent.putExtra("roomName", roomName);
                roomIntent.putExtra("floorSerialNo", floorSerialNo);
                startActivityForResult(roomIntent,777);
                break;
            case R.id.btn_picture:
                showBottomListDialog();
                break;
            case R.id.btn_share:
                Intent intent2 = new Intent(this, RoomShareListActivity.class);
                intent2.putExtra("roomSerialNo", roomSerialNo);
                startActivity(intent2);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case EDIT_ROOM_CODE:
                if(data != null){
                    floorSerialNo = data.getStringExtra("floorSerialNo");
                    floorName = data.getStringExtra("floorName");
                    updateRoomName();
                }
                setResult(RESULT_OK);
                break;
            case 777:
                if(data != null){
                    roomType = data.getStringExtra("roomType");
                    updateRoomName();
                }
                setResult(RESULT_OK);
                break;
        }
    }

    private void showBottomListDialog(){
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(getContext());
            mBottomListDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(getContext());
            listLabelAdapter.setChecekSelect(true);
            List<String> data = new ArrayList<>();
            data.add(getString(R.string.room_picture_gallery));
            data.add("从相册选择");
            data.add("照相");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    mBottomListDialog.dismiss();
                    String key = data.get(position);
                    if(key.equals(getString(R.string.room_picture_gallery))){
                        Intent intent = new Intent(getContext(), RoomGalleryActivity.class);
                        intent.putExtra("roomSerialNo", roomSerialNo);
                        intent.putExtra("roomTypeName",tvRoomType.getText());
                        startActivity(intent);
                    }else if(key.equals("照相")){
                        getImage(SelectImageActivity.ACTION_CAMERA);
                    }else{
                        getImage(SelectImageActivity.ACTION_GALLERY);

                    }
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        mBottomListDialog.show();
    }

    private XXPermissions xxPermissions;
    private void getImage(String action) {
        currentAction = action; // 保存当前action
        if(xxPermissions == null){
            xxPermissions = XXPermissions.with(getContext());
        }
        String[] permissions = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };
        if(!XXPermissions.isGranted(getContext(),permissions) && AppApplication.isHuawei() ){
            showConfirmHintDialog("App需要使用您的相机和存储权限，来拍摄和选择房间图片。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的相机和存储权限改为允许。");
        }else{
            requestPermission(action);
        }
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            requestPermission(currentAction); // 使用保存的action
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(String action) {
        xxPermissions.permission( Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            actionProfilePic(action);
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
    }

    private void actionProfilePic(String action) {
        Intent intent = new Intent(getContext(), SelectImageActivity.class);
        intent.setAction(SelectImageActivity.ACTION_RECT);
        intent.putExtra("ACTION", action);
        startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (data!=null && data.getExtras()!=null){
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    String imagePath = data.getExtras().getString(SelectImageActivity.CROP_IMAGE_PATH);
                    updateCropImage(new File(imagePath), true);
                }
            }
        });
    }

    private void updateCropImage(File file, boolean deleteFile) {
        if (file == null) return;
        showDialog();
        String path = String.format("room/custom/custom-%s-%d.jpg", roomSerialNo,System.currentTimeMillis());
        OBSManager.updateImage(path, file, new OBSManager.OBSCallBack() {
            @Override
            public void onSuccess(String imgUrl) {
                if (imgUrl!=null){
                    String imgpath = imgUrl.replace(OBS_BASE.substring(0,OBS_BASE.length()-1), "");
                    savePic(imgpath);
                    hideDialog();
                    if (deleteFile) {
                        file.delete();
                    }
                }
            }

            @Override
            public void onFail() {
                hideDialog();
            }
        });
    }

    public void savePic(String path){
        LLHttpManager.saveRoomPic(this,roomSerialNo,path,new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
                showDialog("请稍后");
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                RoomBean roomBean = LLRoomDBManager.getInstance(getContext()).getRoomByRoomSerialNo(roomSerialNo);
                roomBean.setPicUrl(path);
                LLRoomDBManager.getInstance(getContext()).put(roomBean);
                EventBus.getDefault().post(new RefreshFloorRoomEvent());
                finish();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }
}